from App import db


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(128))
    password = db.Column(db.String(128))

    @classmethod
    def addUser(cls, name, password):
        try:
            user = User(username=name, password=password)
            db.session.add(user)
            db.session.commit()
            return 0
        except:
            print('rolllback')
            db.session.rollback()
            return 1

    @classmethod
    def getUsers(cls):
        return User.query.all()

    @classmethod
    def haveUser(cls, username, password):
        user = User.query.filter_by(username=username, password=password).first()
        if user != None:
            return True
        else:
            return False

class Block(db.Model):
    __tablename__='block'
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(128))
    hots=db.relationship('Hot',
                         backref='block',
                         cascade='all,delete-orphan')

    @classmethod
    def addBolck(cls,name):
        try:
            block=Block(name=name)
            db.session.add(block)
            db.session.commit()
            return 0
        except:
            print('rolllback')
            db.session.rollback()
            return 1

    @classmethod
    def getBlocks(cls):
        return Block.query.all()

class Hot(db.Model):
    __tablename__='hot'
    id = db.Column(db.Integer, primary_key=True)
    title=db.Column(db.Text())
    content=db.Column(db.Text(),nullable=True)
    url=db.Column(db.Text())
    block_id=db.Column(db.Integer,db.ForeignKey('block.id'))

    @classmethod
    def addHot(cls,block,title,content,url):
        try:
            b=Block.query.filter_by(name=block).first().id
            hot=Hot(title=title,content=content,url=url,block_id=b)
            db.session.add(hot)
            db.session.commit()
            return 0
        except:
            print('rolllback')
            db.session.rollback()
            return 1

class LogsDb(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    username=db.Column(db.String(128))
    search_result = db.Column(db.String(128))
    ip = db.Column(db.String(128))
    user_agent = db.Column(db.String(128))

    @classmethod
    def addLogs(cls,username,search_result,ip,user_agent):
        try:
            logs_object = LogsDb(username=username,search_result=search_result,ip=ip,user_agent=user_agent)
            db.session.add(logs_object)
            db.session.commit()
            return 0
        except:
            print('rolllback')
            db.session.rollback()
            return 1

    @classmethod
    def getLogs(cls):
        return LogsDb.query.all()